<template>
  <div>
    <div class="login-header">
      <img src="../assets/img/sinotrans.png" class="header-img">
    </div>
    <div class="login_div">
      <div class="login_container">
        <h3 class="login_title">用户登录</h3>
        <div style="height: 70%">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="账号密码登录" name="first">
              <el-form ref="formMob" :model="loginMob" status-icon :rules="rulesMob"
                       label-width="70px">
                <!-- prop对应rules里的键 -->
                <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="loginMob.mobile" placeholder="手机号码" autocomplete="off"
                            @keyup.enter.native="submit"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input type="password" placeholder="请输入密码" v-model="loginMob.password" autocomplete="off"
                            @keyup.enter.native="submit"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="codeMessage">
                  <el-col :span="11">
                    <el-input style="width: 100px" v-model="loginMob.codeMessage" placeholder="验证码" autocomplete="off"
                              @keyup.enter.native="submit"></el-input>
                  </el-col>
                  <el-col :span="11">
                    <img style="margin-left: 20px"  :src="captchaUrl" alt="captcha"
                         @click="getCaptcha" ref="captcha">
                  </el-col>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <!-- 验证码登录 -->
            <el-tab-pane label="验证码登录" name="second">
              <el-form style="margin-top: 10%" ref="formEmail" :model="loginEmail" status-icon :rules="rulesEmail"
                       label-width="70px">
                <!-- prop对应rules里的键 -->
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="loginEmail.email" placeholder="邮箱" autocomplete="off"
                            @keyup.enter.native="submit"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                  <el-col :span="11">
                    <el-input style="width: 100px" v-model="loginEmail.code" placeholder="验证码" autocomplete="off"
                              @keyup.enter.native="submit"></el-input>
                  </el-col>
                  <el-col :span="11">
                    <el-button style="width: 100px;margin-left: 1px;text-align: center;font-size: 12px;"
                               :disabled="countdown > 0" @click="startCountdown">
                      {{ countdown > 0 ? countdown + '秒' : '获取验证码' }}
                    </el-button>
                  </el-col>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div style="margin-left: 40px;margin-top: 23px">
          <el-button @click="submit" type="primary">登录</el-button>
          <el-button style="margin-left: 70px" @click="clear" type="primary">重置</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import axios from "axios";

export default {
  data() {
    return {
      // 登陆数据
      formParams: '',
      activeName: 'first',
      captchaUrl: 'http://luckycola.com.cn/captcha/getCaptcha?CaptchaSize=60&CaptchaNoise=4&CaptchaW=100&CaptchaH=38&CaptchaNum=4&ColaKey=0o6czNXOl10HCx1703522034337UQ28bGKCuk'+ '&time=' + Date.now(),
      loginMob: {
        mobile: '',
        password: ''
      },
      loginEmail: {
        email: '',
        code: ''
      },
      // 校验规则
      rulesMob: {
        mobile: [{required: 'true', message: '请输入账号', trigger: 'blur'}],
        password: [{required: 'true', message: '请输入密码', trigger: 'blur'}],
        codeMessage:[{required: 'true', message: '请输入密码', trigger: 'blur'}]
      },
      rulesEmail: {
        email: [{required: 'true', message: '请输入邮箱', trigger: 'blur'}],
        code: [{required: 'true', message: '请输入验证码', trigger: 'blur'}]
      },
      //时间倒计时
      countdown: 0,
      timer: null
    }
  },
  methods: {
    getCaptcha(){
      this.captchaUrl = this.captchaUrl + '&time=' + Date.now();
    },
    startCountdown() {
      //异步发送验证码
      // 模拟一个异步操作
      axios.get("/api/login/getLoginCode", {
        params: {
          email: this.loginEmail.email
        }
      }).then((res) => {
        if (res.data.code === 200) {
          this.$message({
            message: res.data.message,
            type: 'success'
          });
        } else {
          this.$message.error(res.data.message);
        }
      })
      this.countdown = 59;
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },
    beforeDestroy() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    watch: {
      countdown: {
        handler(newVal) {
          this.countdown = newVal
        }
      }
    },
    submit() {
      // 表单的校验
      this.captchaUrl = this.captchaUrl + '&time=' + Date.now();
      if (this.activeName === 'first') {
        this.$refs.formMob.validate((valid) => {
          if (valid) {
            this.formParams = {
              mob: this.loginMob.mobile,
              pas: this.loginMob.password
            }
            // axios.post("http://luckycola.com.cn/captcha/validateCaptcha",{
            //   params: {
            //     captcha: this.message,
            //     ColaKey: 'rsTqMzuTTAk94r1698337916350vIo4tSy2Un'
            //   }
            // }).then((codeMs) =>{
            //   const resData = codeMs.data;
            //   if (resData.code !== 0){
            //     this.$message.error("验证码错误！");
            //   }
            // })
            axios.get("/api/login/login", {
              params: this.formParams
            }).then((loginInfo) => {
              if (loginInfo.data.code === 200) {
                //todo
                axios.get("api/config/getPageConfig/", {
                  params: {
                    role: loginInfo.data.result.userInfo.roleId
                  }
                }).then((page) => {
                  if (page.data.code === 200) {
                    // 记录cookie
                    Cookie.set('token', loginInfo.data.result.Token)
                    // 设置菜单
                    this.$store.commit('setMenu', page.data.result)
                    // 动态添加路由
                    this.$store.commit('addMenu', this.$router)
                    // 跳转到首页
                    this.$router.push('/home')
                    // 存储用户信息
                    localStorage.setItem('userInfo', JSON.stringify(loginInfo.data.result.userInfo))
                    localStorage.setItem('Authorization',loginInfo.data.result.Authorization)
                  }
                })
              } else {
                this.$message.error(loginInfo.data.message);
              }
            })
          }
        })
      } else {
        this.$refs.formEmail.validate((valid) => {
          if (valid) {
            this.formParams = {
              code: this.loginEmail.code,
              email: this.loginEmail.email
            }
            axios.get("/api/login/loginByEmail", {
              params: this.formParams
            }).then((loginInfo) => {
              if (loginInfo.data.code === 200) {
                //todo
                axios.get("api/config/getPageConfig/", {
                  params: {
                    role: loginInfo.data.result.userInfo.roleId
                  }
                }).then((page) => {
                  if (page.data.code === 200) {
                    // 记录cookie
                    Cookie.set('token', loginInfo.data.result.Token)
                    // 设置菜单
                    this.$store.commit('setMenu', page.data.result)
                    // 动态添加路由
                    this.$store.commit('addMenu', this.$router)
                    // 跳转到首页
                    this.$router.push('/home')
                    // 存储用户信息
                    localStorage.setItem("userInfo", JSON.stringify(loginInfo.data.result.userInfo))
                  }
                })
              } else {
                this.$message.error(loginInfo.data.message);
              }
            })
          }
        })
      }
    },
    clear() {
      this.loginMob.mobile = ''
      this.loginMob.password = ''
      this.loginEmail.code = ''
      this.loginEmail.email = ''
    }
  }
}
</script>

<style lang="less" scoped>
.login_container {
  width: 360px;
  border: 1px solid #eaeaea;
  // 居中
  margin: 180px auto;
  margin-left: 70%;
  height: 65%;
  padding: 35px 35px 15px 35px;

  // 让padding在width里面
  box-sizing: border-box;

  border-radius: 15px;
  background-color: #fff;
  box-shadow: 0 0 25px #1c62e5;

  .login_title {
    color: #505458;
    // 左右居中
    text-align: center;
    margin-bottom: 20px;
  }

  .el-input {
    width: 198px;
  }
}

.login_div {
  height: calc(100vh - 68px);
  background-image: url('../assets/img/login-bg.png');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 50%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.login-header {
  background: #27449d;
  height: 68px;

  .header-img {
    width: auto;
    padding: 15px;
    height: 40px;
    max-width: 100%;
    max-height: 100%;
  }
}
</style>
